import { PostCollection } from '@prisma/client';
import { TX } from '../db';

type CreateData = {
  userId: bigint;
  title: string;
};

async function create(tx: TX, { userId, title }: CreateData): Promise<PostCollection> {
  const now = new Date();
  return tx.postCollection.create({
    data: {
      userId,
      title,
      createTime: now,
      deleteTime: null,
      updateTime: now,
    },
  });
}

async function countByUserId(tx: TX, userId: bigint): Promise<number> {
  return tx.postCollection.count({ where: { userId } });
}

async function deleteByIdAndUserId(tx: TX, id: bigint, userId: bigint) {
  // TODO: 检查其下的文章是否都已经删除
  await tx.postCollection.delete({ where: { id, userId } });
}

async function findByIdAndUserId(tx: TX, id: bigint, userId: bigint): Promise<PostCollection | null> {
  return tx.postCollection.findFirst({ where: { id, userId } });
}

async function findByUserId(tx: TX, userId: bigint): Promise<PostCollection[]> {
  return tx.postCollection.findMany({ where: { userId }, orderBy: { id: 'desc' } });
}

type UpdateData = {
  userId: bigint;
  title: string;
  id: bigint;
};

async function update(tx: TX, { id, userId, title }: UpdateData) {
  const now = new Date();
  await tx.postCollection.update({
    where: { id, userId },
    data: { title, updateTime: now },
  });
}

export const postCollectionService = {
  create,
  countByUserId,
  deleteByIdAndUserId,
  findByUserId,
  findByIdAndUserId,
  update,
};
